package com.lemi.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lemi.dao.OutletsMapper;
import com.lemi.entity.Client;
import com.lemi.entity.Outlets;
import com.lemi.entity.Role;
import com.lemi.entity.User;
import com.lemi.util.BspEntity;
import com.lemi.util.BspResult;
import com.lemi.util.BspUtils;
import com.lemi.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("outlets")
public class OutletsController {


    @Resource
    private OutletsMapper outletsMapper;


    @RequestMapping("list")
    public String list(Model model, BspEntity bspEntity){
        model.addAttribute("bspEntity",bspEntity);
        return "sys/outlets";
    }

    @RequestMapping("listData")
    @ResponseBody
    public Object listData(BspEntity bspEntity){
        try {
            Example ue = new Example(Outlets.class);
            Example.Criteria criteria = ue.createCriteria();
            criteria.andEqualTo("delFlag",false);

            if(StringUtils.isNotBlank(bspEntity.getName())){
                criteria.andLike("name","%"+bspEntity.getName()+"%");
            }

            PageHelper.startPage(bspEntity.getPage(),bspEntity.getLimit());
            PageHelper.orderBy(bspEntity.getOrderColumn()+" "+bspEntity.getOrderDir());

            List<Outlets> outletses = outletsMapper.selectByExample(ue);
            PageInfo<Outlets> orderPageInfo = new PageInfo<>(outletses);
            bspEntity.setTotal(orderPageInfo.getTotal());
            bspEntity.setListData(outletses);
            return BspResult.ok("",bspEntity);
        }catch (Exception e){
            e.printStackTrace();
            return BspResult.err(Constant.SERVER_ERR);
        }
    }

    @RequestMapping("/import")
    @ResponseBody
    public Object export(@RequestParam("file") MultipartFile file, HttpSession session, HttpServletRequest request, HttpServletResponse response) {

        try {
            User user = (User)session.getAttribute(Constant.SESSION_USER_INFO);

            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            Workbook workbook = null;

            if (ext.equalsIgnoreCase("XLS")) {
                workbook = new HSSFWorkbook(inputStream);
            } else if (ext.equalsIgnoreCase("XLSX")) {
                workbook = new XSSFWorkbook(inputStream);
            }

            List<Outlets> outletses = new ArrayList<>();

            Sheet sheet = workbook.getSheetAt(0);
            for (int i = 0; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                // 如果当前行为空，则加入空，保持行号一致
                if (null == row) {
                    continue;
                }
//               "网点名称,地址,经度,纬度,联系电话"
                if (i == 0) {
                    String importTitle = "";
                    for (int j = 0; j < row.getLastCellNum(); j++) {
                        Cell cell = row.getCell(j);
                        importTitle += BspUtils.getValue(cell).toString() + ",";
                    }
                    importTitle = BspUtils.removeComma(importTitle);
                    if (!Constant.IMPORT_TEMPLATE_OUTLETS.equals(importTitle)) {
                        return BspResult.err("导入网点模板不规范，导入失败");
                    }
                } else {

                    String name = (String) BspUtils.getValue(row.getCell(0));
                    String address = (String) BspUtils.getValue(row.getCell(1));
                    String longitude = (String) BspUtils.getValue(row.getCell(2));
                    String latitude = (String) BspUtils.getValue(row.getCell(3));
                    String contactNumber = (String) BspUtils.getValue(row.getCell(4));
                    if(StringUtils.isBlank(name) || StringUtils.isBlank(address) ||StringUtils.isBlank(longitude)
                            ||StringUtils.isBlank(latitude) ||StringUtils.isBlank(contactNumber)){
                        return BspResult.err("导入记录存在缺失数据，导入失败");
                    }
//                    String clientNo, String name, String phone, String manangerNo, String financialManager, String outlets
                    outletses.add(new Outlets(name,address,longitude,latitude,contactNumber,new Date(),user.getUserName()));
                }
            }

            outletsMapper.insertBatch(outletses);

            return BspResult.ok("导入完成");
        }catch (Exception e){
            e.printStackTrace();
            return BspResult.err(Constant.SERVER_ERR);
        }
    }

    @RequestMapping("edit")
    @ResponseBody
    public Object edit(HttpSession session, Outlets outlets){
        try {
            if(StringUtils.isBlank(outlets.getName()) || StringUtils.isBlank(outlets.getAddress()) || StringUtils.isBlank(outlets.getContactNumber())
                    || StringUtils.isBlank(outlets.getLongitude()) || StringUtils.isBlank(outlets.getLatitude())){
                return BspResult.err("信息不完整");
            }

            Example re = new Example(Outlets.class);
            Example.Criteria criteria = re.createCriteria();
            criteria.andEqualTo("delFlag",false).andEqualTo("name",outlets.getName());

            if(outlets.getId()!=null){
                criteria.andNotEqualTo("id",outlets.getId());
            }

            List<Outlets> outletses = outletsMapper.selectByExample(re);
            if(outletses.size()>0){
                return BspResult.err("网点已存在！");
            }

            User loginUser = (User)session.getAttribute(Constant.SESSION_USER_INFO);

            if(outlets.getId()!=null){//新增
                outlets.setUpdateTime(new Date());
                outlets.setUpdateName(loginUser.getUserName());
                outletsMapper.updateByPrimaryKeySelective(outlets);
            }
            return BspResult.ok();
        }catch (Exception e){
            e.printStackTrace();
            return BspResult.err(Constant.SERVER_ERR);
        }
    }

    @RequestMapping("delete")
    public String delete(HttpSession session,Model model, BspEntity bspEntity){

        if(bspEntity.getId()!=null){
            User loginUser = (User)session.getAttribute(Constant.SESSION_USER_INFO);
            Outlets outlets = new Outlets();
            outlets.setId(bspEntity.getId());
            outlets.setDelFlag(true);
            outlets.setUpdateTime(new Date());
            outlets.setUpdateName(loginUser.getUserName());
            outletsMapper.updateByPrimaryKeySelective(outlets);
        }

        model.addAttribute("bspEntity",bspEntity);
        return list(model, bspEntity);
    }

}
